/* @(#)InitialServlet.java   
 *
 * Project: GS-1
 *
 * Modify Information:
 * =============================================================================
 *   Author       Date       Description
 *   ------------ ---------- ---------------------------------------------------
 *   yonggangguo  2005-12-29 Create this file
 *   Janus Liu    2007-05-22 增加是否正常初始化的属性及方法
 *
 * Copyright Notice:
 * =============================================================================
 *    Copyright (c) 2001-2007 Auto-Parts E-Procurement Co., Ltd. 
 *        No.251-1 Wuning Road, Shanghai, 200063, China All rights reserved.
 *
 *    This software is the confidential and proprietary information of
 *        Auto-Parts E-Procurement Co., Ltd. ("Confidential Information").
 *        You shall not disclose such Confidential Information and shall use it
 *        only in accordance with the terms of the license agreement you entered
 *        into with APEP.
 *
 * Warning:
 * =============================================================================
 * 
 */
package com.hitrust.gs.action;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Timer;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.PropertyConfigurator;

import com.hitrust.gs.autotask.DataDownTask;
import com.hitrust.gs.autotask.GWDataTask;
import com.hitrust.gs.integration.GSServerListener;
import com.hitrust.gs.lib.GSLogWriter;
import com.hitrust.gs.lib.GSSystemConfigurator;
import com.hitrust.gs.lib.db.DBConnectionManager;
import com.hitrust.gs.lib.db.backup.DataTask;
import com.hitrust.gs.shipment.GSShipmentFlowManager;
import com.hitrust.gs.util.date.DateUtil;
import com.hitrust.gs.util.menu.BuildTreeMenu;


/**
 * 初始化系统运行环境的Servlet
 */
public class InitialServlet extends HttpServlet {
    /**
     * 
     */
    private static final long serialVersionUID = 11411765970400960L;
    
    /**
     * 模块是否正常初始化
     */
    private static boolean sServletInitialed = false;
    
    /**
     * 模块是否正常初始化
     * @return true：模块已经初始化；false: 模块未初始化或初始化失败
     */
    public static boolean isInitialed() {
        return sServletInitialed;
    }
    
    public static long IDLE_TIME = 30*60*1000;//默认30分钟
    public static Timer iBakTimer = null;
    public static Timer iDownTimer = null;
    public static Timer iGWDownTimer = null;
    
    /**
     * Servelt initial
     * @param config - Servlet Confiuration of Servlet Container
     * @throws javax.servlet.ServletException
     */
    public void init(ServletConfig aConfig) throws ServletException {
        super.init(aConfig);
        try {
            GSLogWriter.info("===== 初始化集中采购系统初始化模块(InitialServlet) ===== Start");
            GSLogWriter.info("1、系统运行环境参数：");
            Properties tSysProperties = System.getProperties();
            Enumeration tSysPropKeys = tSysProperties.keys();
            while (tSysPropKeys.hasMoreElements()) {
                String tSysPropKey = (String) tSysPropKeys.nextElement();
                GSLogWriter.info("   " + tSysPropKey + " = [" + tSysProperties.getProperty(tSysPropKey) + "]");
            }
            
            GSLogWriter.info("系统初始化开始");
    		GSSystemConfigurator tGSSystemConfigurator = GSSystemConfigurator.getInstance();
    		if(tGSSystemConfigurator == null){
    			GSLogWriter.fatal(this, "======!!!!!!!!!!!!!!!!!! 初始化 [配置文件] 失败 !!!!!!!!!!!!!!!!!!");
    			throw new Exception("系统初始化失败");
    		}
    		GSLogWriter.info("系统初始化结束");
    		
            //1、初始化日志对象
    		GSLogWriter.info("*******************系统 初始化日志对象 开始********************");
            Properties tLog4jProperties = GSSystemConfigurator.getLog4jProerties();
            PropertyConfigurator.configure(tLog4jProperties);
            GSLogWriter.init(org.apache.log4j.Logger.getLogger("gslogger"));
            GSLogWriter.info("*******************系统 初始化日志对象 成功********************");
    
            //2、初始化系统数据源
            GSLogWriter.info("    ------初始化系统[数据源] 开始 ......");
            DBConnectionManager tDBConnectionManager = DBConnectionManager.getInstance();
            Connection tConn = null;
            if (tDBConnectionManager == null ){
                GSLogWriter.fatal(this, "======!!!!!!!!!!!!!!!!!! 初始化 [数据源] 失败 !!!!!!!!!!!!!!!!!!");
                throw new Exception("初始化系统[数据源]失败！");
            } else {
                try{
                    tConn = tDBConnectionManager.getConnection();
                    tConn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    GSLogWriter.fatal(this, "======!!!!!!!!!!!!!!!!!! 初始化 [数据源] 失败 !!!!!!!!!!!!!!!!!!");
                    throw new Exception("初始化系统[数据源]失败！");
                } finally {
                    try {
                        if (tConn != null && !tConn.isClosed()){
                            tConn.close();
                        }
                    } catch (Exception e){
                    }
                }
            }
            GSLogWriter.info("    ======初始化业务管理系统[数据源] 成功。");
    
//            //3、初始化功能树
//            GSLogWriter.info("    ------初始化系统[功能树] 开始 ......");
//            BuildTreeMenu tBuildTreeMenu = BuildTreeMenu.getInstance();
//            if (tBuildTreeMenu == null){
//                GSLogWriter.fatal(this, "======!!!!!!!!!!!!!!!!!! 初始化 [功能树] 失败 !!!!!!!!!!!!!!!!!!");
//                throw new Exception("初始化系统[功能树]失败！");
//            }
//            GSLogWriter.info("    ======初始化系统[功能树] 成功。");
//
//            GSLogWriter.info("===============开始启动SOCKET服务===============");
//            try{
//                String tPort = GSSystemConfigurator.getParam("gs.server.port");
//                GSServerListener gssl = new GSServerListener(Integer.parseInt(tPort));
//                gssl.start();
//                
//            }catch(Exception e){
//                GSLogWriter.error(this,"启动SOCKET服务失败");
//                throw new Exception("启动SOCKET服务异常");
//            }
//            GSLogWriter.info("===============SOCKET服务启动===============");
            
            /* 2008-01-30 by Sindy
            GSLogWriter.info("===============开始初始对账服务定时器===============");
            try {
                GSAuditFlowManager afm = GSAuditFlowManager.getInstance();
                if (afm == null)
                    throw new Exception();
            }
            catch(Exception e){
                GSLogWriter.error(this,"启动对账服务定时器失败");
                throw new Exception("启动对账服务定时器异常");
            }
            
            GSLogWriter.info("===============对账服务定时器启动===============");
            */
            
//            GSLogWriter.info("===============开始初始出货单下载服务定时器===============");
//            try {
//                GSShipmentFlowManager afm = GSShipmentFlowManager.getInstance();
//                if (afm == null)
//                    throw new Exception();
//            }
//            catch(Exception e) {
//                GSLogWriter.error(this,"启动出货单下载服务定时器失败");
//                throw new Exception("启动出货单下载服务定时器异常");
//            }
//            GSLogWriter.info("===============出货单下载服务定时器启动===============");

            
            //初始化备份数据定时器
//            GSLogWriter.info("===============开始初始数据备份的定时器===============");
//            
////          当前时间
//            String tNowTimeStr= DateUtil.getCurrentTime("T", "F");
//            
//            long tNowTime = Long.parseLong(tNowTimeStr.substring(0, 2)) * 60 * 60
//            + Long.parseLong(tNowTimeStr.substring(3, 5)) * 60
//            + Long.parseLong(tNowTimeStr.substring(6, 8));
//            
//    		iBakTimer = new Timer();
//    		// 备份的时间
//    		String sBakTime=GSSystemConfigurator.getParam("gs.backuptime");	
//            if (sBakTime == null || sBakTime.length()<8){
//                sBakTime = "00:30:00";
//            }
//    		long lBakTime = Long.parseLong(sBakTime.substring(0, 2)) * 60
//    				* 60 + Long.parseLong(sBakTime.substring(3, 5)) * 60
//    				+ Long.parseLong(sBakTime.substring(6, 8));
//            long tBakDelay = (lBakTime > tNowTime ? (lBakTime - tNowTime)
//                    : (lBakTime - tNowTime + 24 * 60 * 60)) * 1000;
//         //   iDataTimer.scheduleAtFixedRate(new DataTask(), tDelayTime, 1 * 60 * 1000);// 每天执行一次
//            iBakTimer.scheduleAtFixedRate(new DataTask(), tBakDelay, 24 * 60 * 60 * 1000);// 每天执行一次
//            GSLogWriter.info("===============数据备份的定时器启动===============");
//           
//            
//            iDownTimer = new Timer();
//            String sDownTime = GSSystemConfigurator.getParam("gs.DataDownTime");
//            if (sDownTime == null || sDownTime.length()<8 ){
//                sDownTime = "00:40:00";
//            }
//            long lDownTime = Long.parseLong(sDownTime.substring(0, 2)) * 60
//                       * 60 + Long.parseLong(sDownTime.substring(3, 5)) * 60
//                       + Long.parseLong(sDownTime.substring(6, 8));
//            long tDownDelay = (lDownTime > tNowTime ? (lDownTime - tNowTime)
//                        : (lDownTime - tNowTime + 24 * 60 * 60)) * 1000;
//            iDownTimer.scheduleAtFixedRate(new DataDownTask(), tDownDelay, 24 * 60 * 60 * 1000 );
//            GSLogWriter.info("===============下载网上交易平台数据定时器启动===============");

//            iGWDownTimer = new Timer();
//            String sGWDownTime = GSSystemConfigurator.getParam("gs.GWDataDownTime");
//            if (sGWDownTime == null || sGWDownTime.length()<8 ){
//                sGWDownTime = "00:40:00";
//            }
//            long lGWDownTime = Long.parseLong(sGWDownTime.substring(0, 2)) * 60
//                       * 60 + Long.parseLong(sGWDownTime.substring(3, 5)) * 60
//                       + Long.parseLong(sGWDownTime.substring(6, 8));
//            long tGWDownDelay = (lGWDownTime > tNowTime ? (lGWDownTime - tNowTime)
//                        : (lGWDownTime - tNowTime + 24 * 60 * 60)) * 1000;
//            iGWDownTimer.scheduleAtFixedRate(new GWDataTask(), tGWDownDelay, 24 * 60 * 60 * 1000 );
//            GSLogWriter.info("===============生成仓储集中管理系统数据定时器启动===============");
            
            sServletInitialed = true;
        } catch (Exception e) {
            e.printStackTrace();
            GSLogWriter.fatal("!!! 失败 !!!!!!!!!!!!!!![初始化系统环境] 失败********************");
            throw new ServletException(e);
        } catch (Error err) {
            err.printStackTrace();
            GSLogWriter.fatal("!!! 失败 !!!!!!!!!!!!!!![初始化系统环境] 失败********************");
            throw new ServletException(err);
        } finally {
            System.setProperty("cs.bm.running.status", "1");//1:运行中；0:停止
            GSLogWriter.info("===== 初始化集中采购系统初始化模块(InitialServlet) ===== End");
        }
    }
    
    /**
     * 结束
     */
    public void destroy(){
        //GSBaseConstants.SOCKET_SERVICE_FLAG = "0";
        GSLogWriter.info("===== 卸载集中采购系统初始化模块(InitialServlet) ===== Start");
        try {
        }
        catch (Exception e) {
            GSLogWriter.error("InitialServlet::destroy() - " + e.getClass().getName() + "[" + e.getMessage() + "]");
        }
        catch (Error e) {
            GSLogWriter.error("InitialServlet::destroy() - " + e.getClass().getName() + "[" + e.getMessage() + "]");
        }
        finally {
            GSLogWriter.info("===== 卸载集中采购系统初始化模块(InitialServlet) ===== End");
            GSLogWriter.info("");
        }
        super.destroy();
    }
}
